<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="2">
        <el-button
          type="primary"
          plain
          size="mini"
          icon="el-icon-plus"
          @click="onOpenAddRoleModal"
        >新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="tableData" max-height="500">
      <!--      <el-table-column type="selection" align="center" />-->
      <el-table-column type="index" label="序号" />
      <el-table-column label="角色名称" prop="role_name" align="center" />
      <el-table-column label="权限字符" prop="role_key" align="center" />
      <el-table-column label="排序" prop="role_sort" align="center" />
      <el-table-column label="菜单状态" width="80" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.status ? '禁用' : '启用' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="onOpenModifyRoleModal(scope.$index, scope.row)">修改</el-button>
          <el-button type="text" size="small" @click="onDeleteRole(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--添加或修改岗位信息-->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="roleForm" :model="roleForm" :rules="roleFormRules" label-width="80px">
        <el-form-item prop="role_name" label="角色名称">
          <el-input v-model="roleForm.role_name" />
        </el-form-item>
        <el-form-item prop="role_key" label="权限字符">
          <el-input v-model="roleForm.role_key" />
        </el-form-item>
        <el-form-item label="顺序">
          <el-input-number v-model="roleForm.role_sort" :min="1" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="roleForm.status">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-tree ref="menu" node-key="menu_id" :data="menuTree" show-checkbox :props="treeProps" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="roleForm.remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="open = false">取 消</el-button>
        <el-button size="small" type="primary" @click="onAddOrModifyRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addRoleApi, modifyRoleApi, getRoleListApi, deleteRoleApi } from '@/api/role'
import { getTreeMenuApi } from '@/api/menu'

export default {
  name: 'Role',
  data() {
    return {
      loading: false,
      queryParams: {},
      tableData: [],

      title: '',
      open: false,
      roleForm: {},
      roleFormRules: {
        role_name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        role_key: [
          { required: true, message: '角色标识不能为空', trigger: 'blur' }
        ]
      },
      menuTree: [],
      treeProps: {
        label: 'menu_name',
        children: 'children'
      }
    }
  },
  created() {
    this.onGetTableData()
  },
  methods: {
    onResetQuery() {
      this.queryParams = {}
      this.$resetForm('queryParams')
    },
    /**
     * 重置岗位添加或修改表单
     */
    resetRoleForm() {
      this.roleForm = {
        role_id: undefined,
        role_name: undefined,
        role_key: undefined,
        remark: undefined,
        status: 0,
        role_sort: 1
      }
      this.$resetForm('roleForm')
    },

    /**
     * 打开新增表单弹窗
     */
    onOpenAddRoleModal() {
      this.resetRoleForm()
      this.onGetTreeMenu()
      this.title = '新增角色'
      this.open = true
    },

    /**
     * 打开修改表单弹窗
     * @param index 当前角色数组索引
     * @param post 当前角色信息
     */
    onOpenModifyRoleModal(index, role) {
      this.resetRoleForm()
      this.onGetTreeMenu()
      console.log(role)
      this.roleForm = { ...role, status: +role.status }
      this.title = '修改角色'
      this.open = true
      this.$nextTick(() => {
        this.$refs.menu.setCheckedKeys(role.menu_ids)
      })
    },

    /**
     * 新增或修改岗位信息
     */
    onAddOrModifyRole() {
      this.$refs.roleForm.validate((valid) => {
        if (valid) {
          const params = {
            role_id: this.roleForm.role_id,
            role_name: this.roleForm.role_name,
            role_key: this.roleForm.role_key,
            remark: this.roleForm.remark,
            status: this.roleForm.status,
            role_sort: this.roleForm.role_sort,
            meau_ids: this.$refs.menu.getCheckedKeys()
          }
          // 新增角色
          if (this.roleForm.role_id === undefined) { // 新增岗位
            addRoleApi(params).then((res) => {
              if (res && res.code === 0) {
                this.open = false
                this.$message.success(res.msg)
                this.onGetTableData()
              } else {
                this.$message.error(res.msg)
              }
            })
          } else { // 修改角色
            // 修改部门
            modifyRoleApi(params).then((res) => {
              if (res && res.code === 0) {
                this.open = false
                this.$message.success(res.msg)
                this.onGetTableData()
                this.onGetTreeMenu()
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        }
      })
    },

    /**
     * 获取岗位列表
     */
    onGetTableData() {
      this.loading = true
      const params = {
        ...this.queryParams
      }
      getRoleListApi(params).then((res) => {
        this.loading = false
        if (res && res.code === 0) {
          const list_arr = res.data.map((item) => {
            item.status = +item.status
            return item
          })
          this.tableData = list_arr
        }
      }).catch(() => {
        this.loading = false
      })
    },

    onDeleteRole(index, role) {
      this.$confirm('确认删除当前角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRoleApi(role).then((res) => {
          if (res && res.code === 0) {
            this.onGetTableData()
            this.$message.success(res.msg)
          } else {
            this.$message.error(res.msg)
          }
        })
      })
    },

    onGetTreeMenu() {
      getTreeMenuApi({ status: 0 }).then((res) => {
        if (res && res.code === 0) {
          this.menuTree = res.data
        }
      })
    },

    handleCheckedTreeNodeAll(value, type) {
      if (type === 'menu') {
        console.log(this.menuTree)
        this.$refs.menu.setCheckedNodes(value ? this.menuTree : [])
      }
    }
  }
}
</script>

<style scoped>

</style>
